import {createSlice, PayloadAction} from "@reduxjs/toolkit";
import { RootState } from "../store";


export const orderInitialState = [
    { id: 1, compKey: 'basic',},
    { id: 2, compKey: 'edu', },
    { id: 3, compKey: 'skills', },
    { id: 4, compKey: 'jobIntent',},
    { id: 5, compKey: 'workExp', },
    { id: 6, compKey: 'projectExp', },
    { id: 7, compKey: 'selfEvaluation',},
]

const orderSlice = createSlice({
    name: 'order',
    initialState: orderInitialState,
    reducers: {
        swapByCompKey: (state, action: PayloadAction<{
            dragKey: string | null, hoverKey: string | null
        }>) => {
            const { dragKey, hoverKey }= action.payload
            if (!dragKey || !hoverKey) return;
            // 触发交换, 根据index交换
            const dragItemIdx = state.findIndex(d => d.compKey === dragKey)
            const hoverItemIdx = state.findIndex(d => d.compKey === hoverKey)
            const newList = [...state]
            newList[dragItemIdx] = state[hoverItemIdx]
            newList[hoverItemIdx] = state[dragItemIdx]
            return newList
        },
        reInitOrder: (state, action) => action.payload
    }
})

export default orderSlice.reducer;

export const getOrder = (state: RootState) => state.order;

export const { swapByCompKey, reInitOrder } = orderSlice.actions;


